package cn.cool.utils;

import io.netty.util.internal.ResourcesUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.UUID;


/**
 * @author LU
 */
@Component
public class UploadUtils {

    /**
     * description: 图片上传
     *
     * @param file
     * @param myPath
     * @return java.lang.String
     */
    public static String upload(MultipartFile file,
                                String myPath) throws FileNotFoundException {
        //myPath:resources/static/images/
        String path = ResourceUtils.getURL("classpath:").getPath() + "/static/images/" + myPath + "/";
        //2原名称
        String originalFilename = file.getOriginalFilename();
        //创建目录
        File fileDir = new File(path);
        if (!fileDir.isDirectory()) {
            // 如果目录不存在，则创建目录
            fileDir.mkdirs();
        }
        //3新名称(uuid随机数加上后缀名)
        String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        //新的图片
        File newFile = new File(path + newFileName);
        try {
            file.transferTo(newFile);
            return newFileName;
        } catch (Exception e) {
            e.printStackTrace();
            return "图片上传失败!";
        }
    }

    /**
     * description: 删除、更新图片
     *
     * @param myPath
     * @return java.lang.Boolean
     */
    public static Boolean deleteImg(String myPath) throws FileNotFoundException {
        //项目路径 myPath:项目图片存放的具体哪个位置
        String path = ResourceUtils.getURL("classpath:").getPath() + "/static" + myPath;
        //删除
        File file = new File(path);
        if (file.exists()) {
            file.delete();
            return true;
        }
        return false;
    }


}

